import java.util.Stack;

public class Solution {
    public String reverseWords(String s) {
        String s1=s.trim();
        Stack<String> stack=new Stack<>();
        String[] s2=s1.split(" ");
        for (String ret:
             s2) {
            stack.push(ret);
        }
        int flag=stack.size();
        String ret1="";
        while(!stack.empty()){
            if(stack.peek().equals(" ")){
                stack.pop();
            }else{
                ret1+=stack.pop();
                if(flag>1){
                    ret1+=" ";
                }
            }
            flag--;
        }
        return ret1;
    }

    public static void main(String[] args) {
        String s="a good   example";
        Solution solution=new Solution();
        String ret=solution.reverseWords(s);
        System.out.println(ret);
    }
}
